﻿using Abp.Domain.Repositories;
using Abp.EntityFrameworkCore;
using Abp.ObjectMapping;
using Abp.UI;
using AVISOutBound.SSOServer.EntityFrameworkCore.Models;
using AVISOutBound.SSOServer.Orders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Abp.Extensions;

namespace AVISOutBound.SSOServer.EntityFrameworkCore.Repositories
{
    public class OrderRepository : SSOServerRepositoryBase<avisOBOrder>, IOrderRepository
    {
        private readonly IRepository<avisOBOrder> _orderRepository;
        private readonly IObjectMapper _objectMapper;

        public OrderRepository(IDbContextProvider<SSOServerDbContext> dbContextProvider,
            IRepository<avisOBOrder> orderRepository,
            IObjectMapper objectMapper)
            : base(dbContextProvider)
        {
            _objectMapper = objectMapper;
            _orderRepository = orderRepository;
        }

        /// <summary>
        /// 获取指定的订单号数据
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <param name="surname">用户的姓</param>
        /// <returns></returns>
        public Order GetOrder(string orderNo, string surname = "")
        {
            Expression<Func<avisOBOrder, bool>> filter = c => c.ReservationNumber == orderNo;
            if (!string.IsNullOrEmpty(surname))
            {
                filter = c => c.ReservationNumber == orderNo && c.Surname == surname;
            }

            var AvisOrder = _orderRepository.FirstOrDefault(filter);
            //var AvisOrderExt = _orderExtRepository.FirstOrDefault(c => c.ReservationNumber == orderNo);
            return MapToOrder(AvisOrder);
        }

        /// <summary>
        /// 保存订单到数据库
        /// </summary>
        /// <param name="order">订单</param>
        public void SaveOrder(Order order)
        {
            // 保存订单信息
            var avisOrder = _orderRepository.FirstOrDefault(a => a.ReservationNumber == order.OrderNo && a.Surname == order.Surname);
            if (avisOrder == null)
            {
                var ao = ToAvisOBOrder(order);
                _orderRepository.Insert(ao);
            }
            else
            {
                var newAvisOrder = ToAvisOBOrder(order, avisOrder);
                _orderRepository.Update(newAvisOrder);
            }

            this.UnitOfWorkManager.Current.SaveChanges();

            //// 保存订单扩展信息
            //var avisOrderExt = _orderExtRepository.FirstOrDefault(a => a.ReservationNumber == order.OrderNo);
            //if (avisOrderExt == null)
            //{
            //    //新建一条数据
            //    avisOrderExt = new avisOBOrderExt();
            //    avisOrderExt.OrderGuid = order.OrderId;
            //    avisOrderExt.ReservationNumber = order.OrderNo;
            //    avisOrderExt.CarGroupJson = JsonConvert.SerializeObject(order.CarGroup);
            //    _orderExtRepository.Insert(avisOrderExt);
            //}
            //else
            //{
            //    avisOrderExt.CarGroupJson = JsonConvert.SerializeObject(order.CarGroup);
            //    _orderExtRepository.Update(avisOrderExt);
            //}
        }

        /// <summary>
        /// 更新订单状态
        /// </summary>
        /// <param name="order">订单</param>
        public async Task UpdateOrderStatus(Order order)
        {
            var data = await this._orderRepository.FirstOrDefaultAsync(a =>
                a.ReservationNumber == order.OrderNo && a.Surname == order.Surname);
            if (data != null)
            {
                data.OrderStatus = order.OrderStatus;
                data.IsCancel = order.IsCancel;
                data.ModifyDate = Abp.Timing.Clock.Now;
                data.ModifyUser = "avis";
                await this._orderRepository.UpdateAsync(data);
            }
        }

        /// <summary>
        /// 取消定单(逻辑删除)
        /// </summary>
        /// <param name="order">订单</param>
        public void CancelOrder(Order order)
        {
            if (order == null
                || string.IsNullOrWhiteSpace(order.OrderNo)
                || string.IsNullOrWhiteSpace(order.Surname))
            {
                throw new UserFriendlyException("对不起，订单信息有误，订单号和姓不能为空");
            }

            var data = _orderRepository.FirstOrDefault(a => a.ReservationNumber == order.OrderNo && a.Surname == order.Surname);
            if (data != null)
            {
                data.IsCancel = order.IsCancel;
                data.CancelReason = order.CancelReason;
                data.ModifyDate = Abp.Timing.Clock.Now;
                data.ModifyUser = "avis";
                _orderRepository.Update(data);
            }
        }

        /// <summary>
        /// 更新订单的YouyouOrderID
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <param name="youyouOrderID"></param>
        public void UpdateYouyouOrderID(string orderNo, int youyouOrderID)
        {
            var data = _orderRepository.FirstOrDefault(a => a.ReservationNumber == orderNo);
            if (data != null)
            {
                data.YouyouOrderID = youyouOrderID;
                _orderRepository.Update(data);
            }
        }

        /// <summary>
        /// 获取过期订单列表
        /// </summary>
        /// <returns></returns>
        public List<string> GetExpiredOrders()
        {
            var expiredTime=DateTime.Now.AddMinutes(-30);
            var datas = this._orderRepository.GetAllList(x => x.CreateDate <= expiredTime &&
                                                              (x.OrderStatus == null || x.OrderStatus == 0) &&
                                                              x.PayType == "2").Select(x => x.ReservationNumber)
                .ToList();
            return datas;
        }

        /// <summary>
        /// 更新订单备注
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <param name="remark">备注</param>
        /// <returns></returns>
        public async Task UpdateRemark(string orderNo,string remark)
        {
            if (remark.IsNullOrEmpty())
            {
                return;
            }
            var entity = await this._orderRepository.FirstOrDefaultAsync(x => x.ReservationNumber == orderNo);
            if (entity != null)
            {
                entity.Remark = remark;
                entity.ModifyDate = Abp.Timing.Clock.Now;
                entity.ModifyUser = "avis";
                await this._orderRepository.UpdateAsync(entity);
            }
        }

        #region 私有方法
        /// <summary>
        /// 将订单转为AVIS订单对象
        /// </summary>
        /// <param name="realAWD">AWD</param>
        /// <param name="Order">订单</param>
        /// <param name="obOrder">AVIS订单</param>
        /// <returns></returns>
        private avisOBOrder ToAvisOBOrder(Order Order, avisOBOrder obOrder = null)
        {
            if (obOrder == null)
            {
                obOrder = new avisOBOrder();
                obOrder = _objectMapper.Map<avisOBOrder>(Order);
                obOrder.Postcode = obOrder.Postcode == null ? "" : obOrder.Postcode;
                obOrder.IsSendMessage = obOrder.IsSendMessage.HasValue ? obOrder.IsSendMessage : false;
                obOrder.DiscountCost = obOrder.DiscountCost.HasValue ? obOrder.DiscountCost : 0;
                obOrder.IsNoFlightNumber = obOrder.IsNoFlightNumber.HasValue ? obOrder.IsNoFlightNumber : false;

                obOrder.CardNum = "";
                obOrder.AmountCNY = Order.RMBAmount;
                obOrder.Remark = string.IsNullOrEmpty(obOrder.Remark) ? "" : obOrder.Remark;
                obOrder.YouyouOrderID = 0;
                obOrder.IsEmail = false;
                obOrder.CreateDate = Abp.Timing.Clock.Now;
                obOrder.CreateUser = "avis";
                obOrder.ModifyDate = Abp.Timing.Clock.Now;
                obOrder.ModifyUser = "avis";

            }
            else
            {
                // 从请求的Order复制修改的属性值到avisOBOrder对象（obOrder）
                _objectMapper.Map(Order, obOrder);

                obOrder.CardNum = "";
                obOrder.AmountCNY = Order.RMBAmount;
                obOrder.Remark = string.IsNullOrEmpty(obOrder.Remark) ? "" : obOrder.Remark;
                obOrder.YouyouOrderID = 0;
                obOrder.IsEmail = false;
                obOrder.ModifyDate = Abp.Timing.Clock.Now;
                obOrder.ModifyUser = "avis";
            }

            return obOrder;
        }

        /// <summary>
        /// 将AVIS订单对象转为Order对象
        /// </summary>
        /// <param name="AvisOrder"></param>
        /// <param name="AvisOrderExt"></param>
        /// <returns></returns>
        private Order MapToOrder(avisOBOrder AvisOrder)
        {
            if (AvisOrder != null)
            {
                var data = _objectMapper.Map<Order>(AvisOrder);
                data.OrderStep = 7;
                data.RentalUnit = "天";

                //if (AvisOrderExt != null)
                //{
                //    data.OrderId = AvisOrderExt.OrderGuid;
                //    data.CarGroup = JsonConvert.DeserializeObject<CarGroup>(AvisOrderExt.CarGroupJson);
                //}

                return data;
            }

            return null;
        }
        #endregion
    }
}
